# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName:   ApiTest
# FileName:      read_user_ini.py
# Author:       liu
# Datetime:     2024/9/7 上午11:00
# Description: 读取用户ini文件
# ---------------------------------------------------------------------------
import os
from configparser import ConfigParser

from ApiTest.report import log


class Read_user_ini:
    def __init__(self, username):
        # 获取用户的文件，判断用户目录是否存在
        config_data = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'config_data')
        self.user_dir = os.path.join(config_data, username)
        if os.path.isdir(self.user_dir):
            pass
        else:
            log.error(f'用户{username}的目录不存在于{config_data}中')
            raise KeyError(f"用户{username}的目录不存在于{config_data}中")
        user_ini = os.path.join(self.user_dir, 'config.ini')
        # 初始化
        self.config = ConfigParser()
        # 读取ini文件
        self.config.read(user_ini, encoding='utf-8')

    def get_file(self, key):
        try:
            file_path = os.path.join(self.user_dir, self.config.get('file', key))
            log.info(f'使用get_file方法读取{key}的值，得到{file_path}的文件路径')
            return file_path
        except Exception as e:
            log.error(f'key：{key}传值错误，请确定key存在且没有填写错误')
            raise e

    def get_table(self, key):
        try:
            table = self.config.get('table', key)
            log.info(f'使用get_table方法读取{key}的值，得到用户excel文件中的{table}表名')
            return table
        except Exception as e:
            log.error(f'key：{key}传值错误，请确定key存在且没有填写错误')
            raise e


if __name__ == '__main__':
    read_ini = Read_user_ini(username='test_demo')
    print(read_ini.get_file('excel'))
    print(read_ini.get_table('sheet1'))